import 'dart:convert';
import 'dart:io';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/fwebView_scaffold.dart';
import 'package:gzmall_app/common/launch_util.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/model/user.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:gzmall_app/common/auth_login_util.dart';
import 'package:gzmall_app/login/third_auth_login_page.dart';

class LoginPage extends StatefulWidget {
  LoginPage({Key key}) : super(key: key);

  @override
  _LoginPageSate createState() => _LoginPageSate();
}

class _LoginPageSate extends State<LoginPage> {
  SystemUiOverlayStyle _style = SystemUiOverlayStyle.dark;
  String _account;
  String _password;
  User _user = User.empty();
  TextEditingController _accountController, _passwordController;

  @override
  void initState() {
    super.initState();
    _accountController = TextEditingController();
    _passwordController = TextEditingController();
    User.isInLogin = true;
    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is fluwx.WeChatAuthResponse) {
        String result = 'errCode ' +
            res.errCode.toString() +
            '\n' +
            'country ' +
            res.country +
            '\n' +
            'lang ' +
            res.lang +
            '\n' +
            'code ' +
            res.code +
            '\n' +
            'state ' +
            res.state +
            '\n';
        print("<fluwx> responseFromAuth ${result}");

        if (res.code != null) {
          _getWxAccessToken(res.code);
        }
      }
    });

    _getUserInfo();
  }

  @override
  void dispose() {
    _style = SystemUiOverlayStyle.light;
    SystemChrome.setSystemUIOverlayStyle(_style);
    User.isInLogin = false;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(_style);
    return new Scaffold(
      body: ListView(
        children: <Widget>[
          Column(
            children: <Widget>[
              new Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  new Expanded(
                    child: new Align(
                      alignment: Alignment.centerLeft,
                      child: new IconButton(
                        padding: EdgeInsets.only(left: 10.0),
                        icon: new Icon(Icons.close),
                        tooltip: "关闭",
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                    ),
                  ),
                  new GestureDetector(
                    child: new Padding(
                      padding: EdgeInsets.only(right: 15.0),
                      child: new Text(
                        "注册",
                        style:
                            new TextStyle(color: Colors.blue, fontSize: 16.0),
                      ),
                    ),
                    onTap: () {
                      Navigator.of(context).pushNamed('/register_page');
                    },
                  ),
                ],
              ),
              new Container(
                margin: const EdgeInsets.only(top: 30.0, bottom: 10.0),
                width: 75.0,
                height: 75.0,
                decoration: _user != null &&
                        _user.avatar != null &&
                        _user.avatar.isNotEmpty
                    ? new BoxDecoration(
                        color: Colors.grey,
                        borderRadius: new BorderRadius.circular(100.0),
                        image: new DecorationImage(
                            image: new CachedNetworkImageProvider(_user.avatar),
                            fit: BoxFit.fill),
                      )
                    : BoxDecoration(
                        color: Colors.grey,
                        borderRadius: new BorderRadius.circular(100.0),
                      ),
              ),
              new Text(
                _user.nickname != null && _user.nickname.isNotEmpty
                    ? _user.nickname
                    : "用户名",
                style: new TextStyle(color: ColorCommon.black1),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  new Container(
                    height: 54.0,
                    padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                    margin: const EdgeInsets.only(
                        left: 30.0, right: 30.0, bottom: 20.0, top: 30.0),
                    alignment: Alignment.center,
                    decoration: new BoxDecoration(
                        color: ColorCommon.grey2,
                        borderRadius: new BorderRadius.circular(100.0)),
                    child: new Row(
                      children: <Widget>[
                        new Expanded(
                          child: new TextField(
                            controller: _accountController,
                            style: new TextStyle(color: ColorCommon.black1),
                            decoration: new InputDecoration.collapsed(
                              hintText: "账号",
                              hintStyle: TextStyle(
                                  fontSize: 12.0, color: ColorCommon.grey1),
                            ),
                            onChanged: (str) {
                              _account = str ?? "";
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  new Container(
                    height: 54.0,
                    padding: const EdgeInsets.only(left: 20.0, right: 20.0),
                    margin: const EdgeInsets.only(
                        left: 30.0, right: 30.0, bottom: 30.0),
                    alignment: Alignment.center,
                    decoration: new BoxDecoration(
                        color: ColorCommon.grey2,
                        borderRadius: new BorderRadius.circular(100.0)),
                    child: new Row(
                      children: <Widget>[
                        new Expanded(
                          child: new TextField(
                            obscureText: true,
                            controller: _passwordController,
                            style: new TextStyle(color: ColorCommon.black1),
                            decoration: new InputDecoration.collapsed(
                              hintText: "请输入密码",
                              hintStyle: TextStyle(
                                  fontSize: 12.0, color: ColorCommon.grey1),
                            ),
                            onChanged: (str) {
                              _password = str ?? "";
                            },
                          ),
                        ),
                        new GestureDetector(
                          child: new Text(
                            "忘记密码",
                            textAlign: TextAlign.right,
                            style: new TextStyle(color: ColorCommon.black1),
                          ),
                          onTap: () {
                            Navigator.of(context).pushNamed("/reset_password");
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
          LaunchUtil.isInstallWeixin && !SettingUtil.isAppStoreAudit()
              ? new GestureDetector(
                  child: Align(
                    child: Text(
                      "更多登录方式",
                      style: new TextStyle(color: ColorCommon.black1),
                    ),
                  ),
                  onTap: () {
                    AuthLoginUtil.showAuthSelect(context);
                  },
                )
              : Container(),
          new GestureDetector(
            onTap: () {
              _loginAction();
            },
            child: new Container(
              height: 54.0,
              margin: const EdgeInsets.fromLTRB(30.0, 20.0, 30.0, 50.0),
              alignment: Alignment.center,
              decoration: new BoxDecoration(
                  color: ColorCommon.primaryColor,
                  borderRadius: new BorderRadius.circular(100.0)),
              child: new Text(
                "立即进入",
                style: new TextStyle(color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _loginAction() {
    if (_account == null || _account.isEmpty) {
      ToastUtil.showMessageToast("请输入账号");
      return;
    }
    if (_password == null || _password.isEmpty) {
      ToastUtil.showMessageToast("请输入密码");
      return;
    }

    _login(_account, _password, "registration_id");
  }

  _login(String phone, String password, String registrationId) {
    Map<String, String> params = {
      "phone": phone,
      "password": password,
      "registration_id": registrationId,
    };

    NetUtil.post(context, Api.userLogin, (data, message) {
      ToastUtil.showMessageToast(message);
      User user = User.fromJson(data);
      User.saveUserToken(user.authToken);
      User.saveUserInfo(user);
      Navigator.of(context).pop();
    }, params: params, isShowLoading: true);
  }

  _getUserInfo() async {
    await _user.getUserInfo();
    if (!mounted) return;
    setState(() {});

    Future.delayed(const Duration(milliseconds: 3000), () {
      if (Platform.isAndroid) {
        User.getIsShowPrivacy().then((v) {
          if (!v || v == null) {
            _showPrivacyDialog();
          }
        });
      }
    });
  }

  _getWxAccessToken(String code) async {
    Map<String, String> params = {
      "appid": Api.wxAppId,
      "secret": Api.wxAppSecret,
      "code": code,
      "grant_type": 'authorization_code',
    };

    Dio dio = new Dio();
    dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));

    Response response = await dio.get(
        "https://api.weixin.qq.com/sns/oauth2/access_token",
        queryParameters: params);
    final responseData = json.decode(response.data.toString());
    print("<_getWxAccessToken> data ${responseData.toString()}");
    if (responseData.toString().contains("access_token")) {
      String _responseResult = '';
      if (responseData['access_token'] != null) {
        _responseResult += "access_token ${responseData['access_token']} \n";
      }
      if (responseData['expires_in'] != null) {
        _responseResult += "expires_in ${responseData['expires_in']} \n";
      }
      if (responseData['refresh_token'] != null) {
        _responseResult += "refresh_token ${responseData['refresh_token']} \n";
      }
      if (responseData['openid'] != null) {
        _responseResult += "openid ${responseData['openid']} \n";
      }
      if (responseData['scope'] != null) {
        _responseResult += "scope ${responseData['scope']} \n";
      }
      if (responseData['unionid'] != null) {
        _responseResult += "unionid ${responseData['unionid']} \n";
      }
      print("<_getWxAccessToken> _responseResult ${_responseResult}");

      if (responseData['openid'] != null) {
        Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          return ThirdAuthLoginPage(responseData['openid']);
        })).then((v) {
          if (v) {
            Navigator.of(context).pop();
          }
        });
      }
    } else {
      String _errorResult = '';
      if (responseData['errcode'] != null) {
        _errorResult += "errcode ${responseData['errcode']} \n";
      }
      if (responseData['errmsg'] != null) {
        _errorResult += "errmsg ${responseData['errmsg']} \n";
      }
      print("<_getWxAccessToken> _errorResult ${_errorResult}");
    }
  }

  /// 用户协议中“低调”文本的样式。
  final TextStyle _lowProfileStyle = TextStyle(
    fontSize: 12.0,
    color: Color(0xFF4A4A4A),
  );

  /// 用户协议中“高调”文本的样式。
  final TextStyle _highProfileStyle = TextStyle(
    fontSize: 12.0,
    color: Color(0xFF00CED2),
  );

  _showPrivacyDialog() {
    Text textContent = Text.rich(
      TextSpan(
        text:
            '    感谢您对本公司的支持!本公司非常重视您的个人信息和隐私保护。\n为了更好地保障您的个人权益，在您使用我们的产品前，\n请务必审慎阅读',
        style: _lowProfileStyle,
        children: [
          TextSpan(
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                String html = Uri.dataFromString(Api.privacyPolicy,
                    mimeType: 'text/html',
                    parameters: {'charset': 'utf-8'}).toString();
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return FWebviewScaffold(
                    url: html,
                    userAgent: Api.kWebViewUserAgent,
                    enableMessaging: true,
                    withJavascript: true,
                    clearCache: true,
                    appBar: AppBar(
                      title: Text("隐私政策"),
                    ),
                  );
                }));
              },
            text: '《隐私政策》',
            style: _highProfileStyle,
          ),
          TextSpan(
            text: '和',
            style: _lowProfileStyle,
          ),
          TextSpan(
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                String html = Uri.dataFromString(Api.userAgreement,
                    mimeType: 'text/html',
                    parameters: {'charset': 'utf-8'}).toString();
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return FWebviewScaffold(
                    url: html,
                    userAgent: Api.kWebViewUserAgent,
                    enableMessaging: true,
                    withJavascript: true,
                    clearCache: true,
                    appBar: AppBar(
                      title: Text("用户协议"),
                    ),
                  );
                }));
              },
            text: '《用户协议》',
            style: _highProfileStyle,
          ),
          TextSpan(
              text:
                  '内的所有条款，\n尤其是:\n 1.我们对您的个人信息的收集/保存/使用/对外提供/保护等规则条款，以及您的用户权利等条款;\n 2.约定我们的限制责任、免责条款;\n 3.其他以颜色或加粗进行标识的重要条款。\n如您对以上协议有任何疑问，\n可通过人工客服或发邮件至 2242686462@qq.com 与我们联系。您点击“同意并继续”的行为即表示您已阅读完毕并同意以上协议的全部内容。\n如您同意以上协议内容，请点击“同意”，开始使用我们的产品和服务!',
              style: _lowProfileStyle)
        ],
      ),
    );

    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      child: AlertDialog(content: textContent, actions: <Widget>[
        FlatButton(
            onPressed: () {
              Navigator.pop(context);
              User.saveIsShowPrivacy(true);
            },
            child: Text('同意')),
        FlatButton(
            onPressed: () {
              Navigator.pop(context);
              SystemNavigator.pop();
            },
            child: Text('拒绝'))
      ]),
    );
  }
}
